package io.qar.commons.tools.config;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

@Data
@Configuration
@RefreshScope
@ConfigurationProperties(prefix = "snowflake-config")
public class SnowflakeConfig {
    private Long workerId;
    private Long datacenterId;
    private static Snowflake snowflake;

    /**
     * @PostConstruct 标记的方法保证在所有依赖注入完成后执行，
     * 这意味着 workerId 和 datacenterId 已经被正确地从配置文件中读取并赋值给相应的字段，
     * 从而可以安全地使用它们来初始化 Snowflake 实例
     */
    @PostConstruct
    public void init() {
        if (workerId < 0 || workerId > 1023 || datacenterId < 0 || datacenterId > 31) {
            throw new IllegalArgumentException("Invalid workerId or datacenterId");
        }
        snowflake = IdUtil.getSnowflake(workerId, datacenterId);
    }

    @Bean
    public Snowflake getSnowflake() {
        return snowflake;
    }

    public synchronized long nextId() {
        return snowflake.nextId();
    }
}